import json
import plugins
from bridge.context import ContextType
from bridge.reply import Reply, ReplyType
from channel.chat_message import ChatMessage
from common.log import logger
from plugins import *
from config import conf
from .utils import request

@plugins.register(
    name="JMServer",
    desire_priority=88,
    hidden=False,
    desc="金目鼎盛服务端自用插件",
    version="0.1",
    author="tyguigui",
)

class JMServer(Plugin):
    def __init__(self):
        super().__init__()
        self.handlers[Event.ON_HANDLE_CONTEXT] = self.on_handle_context
        logger.info("[JMServer] inited")

    def on_handle_context(self, e_context: EventContext):

        # 判断消息类型，如果不是文字直接跳出
        if e_context['context'].type != ContextType.TEXT:
            return

        # 获取消息内容存为content做后续处理
        content = e_context['context'].content

        # 功能列表
        if content == "功能" or content == "帮助":
            reply = Reply()
            reply.type = ReplyType.TEXT
            msg:ChatMessage = e_context['context']['msg']
            reply.content = get_function_list_reply_contend()
            e_context['reply'] = reply
            e_context.action = EventAction.BREAK_PASS # 事件结束，并跳过处理context的默认逻辑

        # 查看服务器状态
        if content == "接口测试":
            try:
                json_file_path = os.path.join(os.path.dirname(__file__), 'config.json')
            except Exception as e:
                return self.handle_error(e, "读取config.json失败")
            
            with open(json_file_path, 'r', encoding='utf-8') as f:
                BASE_URL = json.load(f)['jm_api_base_url']
            
            reply = Reply()
            reply.type = ReplyType.TEXT
            msg:ChatMessage = e_context['context']['msg']
            url = f"{BASE_URL}/test/server"
            res = request(url)
            reply.content = f"{res}"
            e_context['reply'] = reply
            e_context.action = EventAction.BREAK_PASS # 事件结束，并跳过处理context的默认逻辑

        # 测试用
        if content == "Hello":
            reply = Reply()
            reply.type = ReplyType.TEXT
            msg:ChatMessage = e_context['context']['msg']
            if e_context['context']['isgroup']:
                reply.content = f"Hello呀, {msg.actual_user_nickname} from {msg.from_user_nickname}"
            else:
                reply.content = f"Hello呀, {msg.from_user_nickname}"
            e_context['reply'] = reply
            e_context.action = EventAction.BREAK_PASS # 事件结束，并跳过处理context的默认逻辑

# 根据功能列表生成便于用户阅读的字符串
def get_function_list_reply_contend():
    try:
        json_file_path = os.path.join(os.path.dirname(__file__), 'function_list.json')
    except Exception as e:
        return self.handle_error(e, "function_list.json失败")

    with open(json_file_path, 'r', encoding='utf-8') as f:
        function_json = json.load(f)
        function_list = function_json['function_list']
        update_time = function_json['update_time']
        author = function_json['author']
        contend = "我目前的功能如下:\n(使用时不需要像举例一样加引号):\n\n"
        for func in function_list:
            contend += f"【{func['name']}】{func['desc']}\n"
            contend += f"📝 使用方法:\n"
            contend += f"{func['use']}\n"
            if "eg" in func:
                contend += f"📝 比如发送:\n"
                for eg in func['eg']:
                    contend += f"{eg}\n"
            contend += "\n"
        contend += f"更新日期：{update_time} {author}"
        return contend
    
    